package com.sagittarius.demo.common;

import com.sagittarius.demo.enums.ResultCodeEnum;
import lombok.Data;

import java.io.Serializable;

/**
 * @ClassName Result.java
 * @Author 李瑞珂
 * @Version 1.0.0
 * @Description 自定义返回类
 * @CreateTime 2022年04月30日 16:18:00
 */
@Data
public class Result<T> implements Serializable {

    /**
     * 成功状态码
     */
    public static final int SUCCESS_CODE = ResultCodeEnum.SUCCESS.getCode();
    /**
     * 成功信息
     */
    public static final String SUCCESS_MESSAGE = ResultCodeEnum.SUCCESS.getMessage();

    /**
     * 失败状态码
     */
    public static final int FAIL_CODE = ResultCodeEnum.FAIL.getCode();
    /**
     * 失败信息
     */
    public static final String FAIL_MESSAGE = ResultCodeEnum.FAIL.getMessage();
    /**
     * 返回头
     */
    private Header header;
    /**
     * 返回内容
     */
    private T payload;

    @Data
    public static class Header{

        private int code;

        private String message;

        public Header(int code,String message){
            this.code = code;
            this.message = message;
        }

    }

    public static <T> Result<T> ok() {
        return restResult(null, SUCCESS_CODE, SUCCESS_MESSAGE);
    }

    public static <T> Result<T> ok(T data) {
        return restResult(data, SUCCESS_CODE, SUCCESS_MESSAGE);
    }

    public static <T> Result<T> ok(String message) {
        return restResult(null, SUCCESS_CODE, message);
    }

    public static <T> Result<T> ok(String message, T data) {
        return restResult(data, SUCCESS_CODE, message);
    }

    public static <T> Result<T> fail() {
        return restResult(null, FAIL_CODE, FAIL_MESSAGE);
    }

    public static <T> Result<T> fail(String message) {
        return restResult(null, FAIL_CODE, message);
    }

    public static <T> Result<T> fail(T data) {
        return restResult(data, FAIL_CODE, FAIL_MESSAGE);
    }

    public static <T> Result<T> fail(String message, T data) {
        return restResult(data, FAIL_CODE, message);
    }

    public static <T> Result<T> fail(int code, String message) {
        return restResult(null, code, message);
    }

    private static <T> Result<T> restResult(T data, int code, String message) {
        Result<T> result = new Result<>();
        result.setHeader(new Header(code,message));
        result.setPayload(data);
        return result;
    }
}
